package MainTest;
import java.sql.*;
import java.util.Random;

public class ConnectMariadbTest {
    static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
    //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mariadb://101.35.166.181:3306/work";
    static final String USER = "guest";//给个账号，只有select的权限
    static final String PASS = "123456";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;

            Random rand =new Random();
            int i = rand.nextInt(8)+1;

            sql = "SELECT * FROM food where id = "+ i;
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("shop");
                String url = rs.getString("eatHow");
                int price = rs.getInt("price");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 饭店名称: " + name);
                System.out.print(", 吃什么: " + url);
                System.out.println(",价格为：" + price);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}
